using System;
using System.Diagnostics;
using System.Globalization;
using PostSharp.Sdk.CodeModel;

namespace CriticalSystems.Instrumentation.Weaver
{
    internal static class Utilities
    {
        public static void DumpBlock(InstructionBlock block, int i, bool recurse, bool parentsOfLeaves)
        {
            if (i == 0)
            {
                DebugWriteLine("DumpBlock");
                DebugWriteLine("----------");
            }
            DebugWriteLine("{0} Block {1} - {2}", GetIndentString(i, '.'), block.Comment, block);
            var sequence = block.FirstInstructionSequence;
            while (sequence != null)
            {
                DebugWriteLine("{0} Sequence {1} - {2}", GetIndentString(i + 1, '-'), sequence.Comment, sequence);
                sequence = sequence.NextSiblingSequence;
            }
            if (recurse)
            {
                var children = block.GetChildrenEnumerator();
                while (children.MoveNext())
                    DumpBlock(children.Current, i + 1, true, parentsOfLeaves);
                if (!block.HasInstructionSequences && !block.HasChildrenBlocks)
                {
                    if (block.ParentBlock != null && parentsOfLeaves)
                    {
                        DebugWriteLine("{0} - Dumping parent", GetIndentString(i + 1, '*'));
                        DumpBlock(block.ParentBlock, i + 1, true, false);
                        DebugWriteLine("{0} - Dumped parent", GetIndentString(i + 1, '*'));
                    }
                }
            }
        }

        private static string GetIndentString(int indent, char character)
        {
            return indent > 0 ? String.Empty.PadRight(indent, character) : String.Empty;
        }

        public static void DebugWriteLine(string format, params object[] objects)
        {
            Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, format, objects));
        }

    }
}